package com.koylu.caffein.converter;

import java.lang.reflect.Method;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class EnumConverter extends GenericConverter{
	
	private Method nameMethod = null;
	private Object[] nameMethodParameter = new Object[]{};
	private Class enumClass = null;
	
	public void setFieldType(Class<?> fieldType){
		enumClass = fieldType;
		try {
			nameMethod = enumClass.getMethod("name", new Class[]{});	
		} catch (Exception e) {}
	}
	
	public Object columnToField(ResultSet resultSet, int index) throws Exception {
		return Enum.valueOf( enumClass, resultSet.getString(index));
	}
	
	public Object columnToField(CallableStatement callableStatement, int index) throws Exception {
		return Enum.valueOf( enumClass, callableStatement.getString(index));
	}
	
	public Object columnToField(ResultSet resultSet, String column) throws Exception {
		return Enum.valueOf( enumClass, resultSet.getString(column));
	}
	
	public void fieldToColumn(PreparedStatement preparedStatement, Object value, boolean columnNullable, int index) throws Exception {
		preparedStatement.setString(index, nameMethod.invoke(value, nameMethodParameter).toString());
	}
}